package com.hope.hotel.config;


import com.hope.hotel.utils.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    private static final List<String> WHITE_LIST_URLS = Arrays.asList(
            "/user/login",
            "/user/register",
            "/user/send-code",
            "/user/info",
            "/user/upload-avatar",
            "/admin/login",
            "/alipay/pay",
            "/alipay/notify",
            "/rabbitMQ/send",
            "/payment/**"
    );

    // 管理员
    private static final List<String> ADMIN_URLS = Arrays.asList("/admin/**");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        String requestURI = request.getRequestURI();
        // 打印所有请求头
        String token = request.getHeader("Authorization");
        System.out.println("拦截器拦截到请求: " + requestURI+" \ntoken:" + token);

        // 处理跨域请求（直接放行预检请求）
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }
        //  白名单放行
        for (String whiteUrl : WHITE_LIST_URLS) {
            // 检查是否为通配符路径
            if (whiteUrl.endsWith("/**")) {
                String prefix = whiteUrl.substring(0, whiteUrl.length() - 2); // 删除 "**"
                if (requestURI.startsWith(prefix)) {
                    System.out.println("通配符匹配放行！" + requestURI);
                    return true;
                }
            } else {
                // 精确匹配
                if (whiteUrl.equals(requestURI)) {
                    System.out.println("精确匹配放行！" + requestURI);
                    return true;
                }
            }
        }

        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                if (TokenUtil.validateToken(token)) {
                    String Id = TokenUtil.getUserId(token);
                    String userRole = TokenUtil.getUserRole(token);
                    if(Objects.equals(userRole, "admin")){
                        request.setAttribute("adminId", Id);
                    }else {
                        request.setAttribute("userId", Id);
                    }
                    return true;
                } else {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write("拦截器出现错误");
                    return false;
                }
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("token过期");
                return false;
            }
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("不存在Token");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // This method is called after the handler execution.
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // This method is called after the complete request has finished.
    }
}
